import store from '@/store/index'
import { getToken, getTokenKey } from '@/utils/auth'
import { tansParams } from '@/utils/common'
import { baseUrl } from '@/config'

let timeout = 60 * 1000

const request = (config: any) => {
  // 是否需要设置 token
  const token = getToken()
  config.header = config.header || {}
  if (token) {
    config.header[getTokenKey()] = token
  }
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params)
    url = url.slice(0, -1)
    config.url = url
  }
  return new Promise<any>((resolve: any, reject: any) => {
    uni.request({
      method: config.method || 'get',
      timeout: config.timeout || timeout,
      url: config.baseUrl || baseUrl + config.url,
      data: config.data,
      header: config.header,
      dataType: 'json'
    }).then((response: any) => {
      const { error, data } = response
      if (error) {
        return reject({ tips: '系统异常，请稍后再试' })
      }
      if (data.code === '0') {
        return resolve(data)
      }
      if (data.code === '1002' || data.code === '1003') {
        store.dispatch('LogoutLocal').then(() => {
          uni.reLaunch({ url: '/pages/login/index' })
        }).catch(() => {
          uni.reLaunch({ url: '/pages/login/index' })
        })
      }
      return reject(data)
    }).catch((error: any) => {
      let { errMsg } = error
      if (errMsg === 'Network Error') {
        errMsg = '网络异常，请稍后再试'
      } else if (errMsg.indexOf('timeout') >= 0) {
        errMsg = '请求超时，请稍后再试'
      } else {
        errMsg = '系统异常，请稍后再试'
      }
      return reject({ tips: errMsg })
    })
  })
}

export default request